<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Config;
use think\facade\Request;
use app\model\Template as TemplateModel;
use mikkle\tp_tools\Rand;

class TemplateController extends BaseController
{

    public function mock()
    {
        Db::name('template')->where('id', '>', 0)->delete();
        $allData = [];
        for ($i = 0; $i < 100; $i++) {
            $data['title'] = '内容一' . $i;
            $data['content'] = 'content' . $i;
            $data['create_time'] = time();
            $data['update_time'] = time();
            $data['delete_time'] = 0;
            $allData[] = $data;
        }
        $mo = new TemplateModel();
        $mo->insertAll($allData);
    }

    public function index(Request $request)
    {
        $fields[0] = ['id' => 'id', 'user_name' => '用户名', 'mobile' => '手机号', 'create_time' => '创建时间', 'last_login_time' => '最后登录时间', 'status' => '状态'];
        $fields[1] = ['id', 'title', 'content', 'create_time'];
        $list['header'] = $fields[0];

        $pageSize = $request::param('pageSize', 10);
        $list = TemplateModel::field($fields[1])->paginate($pageSize, false, [])->toArray();
        return $this->returnPageJson(1001, '返回数据成功', $list);
    }


    public function createRand(Request $request)
    {
        $userInfo = getLoginInfo();
        if ($userInfo != false) {
            if (isExpiration()) {
                return $this->returnJson(1002, '对不起，您的账号已到期！');
            }
        } else {
            return $this->returnJson(1004, '请先登录');
        }

        $param = $request::param();
        $dataValue = [];
        $dataHeader = [];
        if (!empty($param['form']['company'])) {
            $dataValue[] = $param['form']['company'];
            $dataHeader[$param['form']['company']] = '公司名';
        }
        if (!empty($param['form']['site'])) {
            $dataValue[] = $param['form']['site'];
            $dataHeader[$param['form']['site']] = '网址';
        }
        if (!empty($param['form']['email'])) {
            $dataValue[] = $param['form']['email'];
            $dataHeader[$param['form']['email']] = '邮箱';
        }


        $zhiLing = Db::name('template')->where('id', '=', $param['id'])->field('id,content,is_site,and_or,before_after')->find();


        if (count($dataValue) > 1) {
            $resultValue = $this->getAllPermutation($dataValue);
            //            dump($resultValue);
            //            $resultHeader = $this->getAllPermutation($dataHeader);
            $list = [];
            for ($i = 0; $i < count($resultValue); $i++) {
                $value = '';
                $header = '';
                for ($j = 0; $j < count($resultValue[$i]); $j++) {
                    if (count($resultValue[$i]) - 1 == $j) {
                        $value = $value . '"' . $resultValue[$i][$j] . '" ';
                        $header = $header . $dataHeader[$resultValue[$i][$j]] . ' ';
                    } else {
                        $value = $value . '"' . $resultValue[$i][$j] . '" ' . $zhiLing['and_or'] . ' ';
                        $header = $header . $dataHeader[$resultValue[$i][$j]] . '| ';
                    }
                }
                $createString = Rand::createNonceStr(22);
                $createString32 = Rand::createNonceStr(32);
                $retZl = $zhiLing['before_after'] == 1 ? $value . $zhiLing['content'] : $zhiLing['content'] . '(' . $value . ')';
                $url = "https://www.google.com/search?ei=$createString&q=$retZl&oq=$retZl&gs_l=$createString32";
                $list[] = ['name' => $header, 'value' => $retZl, 'url' => $url, 'is_site' => $zhiLing['is_site']];
            }
        } else {
            $createString = Rand::createNonceStr(22);
            $createString32 = Rand::createNonceStr(32);
            $retZl = $zhiLing['before_after'] == 1 ? '"' . $dataValue[0] . '" ' . $zhiLing['content'] : $zhiLing['content'] . ' ("' . $dataValue[0] . '") ';
            $url = "https://www.google.com/search?ei=$createString&q=$retZl&oq=$retZl&gs_l=$createString32";
            $name = '';
            foreach ($dataHeader as $item) {
                $name = $item;
            }
            $list[] = ['name' => $name, 'value' => $retZl, 'url' => $url, 'is_site' => $zhiLing['is_site']];
        }


        return $this->returnJson(1001, 'ok', $list);


    }

    public static function getAllPermutation($array)
    {
        sort($array);
        $last = count($array) - 1;
        $x = $last;
        $count = 1;
        $arr = array($array);
        while (true) {
            $y = $x--;
            if ($array[$x] < $array[$y]) {
                $z = $last;
                while ($array[$x] > $array[$z]) {
                    $z--;
                }
                list($array[$x], $array[$z]) = array($array[$z], $array[$x]);
                for ($i = $last; $i > $y; $i--, $y++) {
                    list($array[$i], $array[$y]) = array($array[$y], $array[$i]);
                }
                array_push($arr, $array);
                $x = $last;
                $count++;
            }

            if ($x == 0) {
                break;
            }
        }
        return self::arrFilter($arr);
    }

    private static function arrFilter($arr)
    {
        $ret = [];
        if (count($arr) > 0) {
            if (count($arr[0]) == 3) {
                $item = [];
                foreach ($arr as $value) {
                    $item[] = [$value[0], $value[1]];
                }
                $item2 = [[$arr[0][0]], [$arr[0][1]], [$arr[0][2]]];
                $ret = array_merge($arr, $item, $item2);
            } else if (count($arr[0]) > 1) {
                foreach ($arr as $value) {
                    $item[] = [$value[0]];
                }
                $ret = array_merge($arr, $item);
            } else {
                $ret = $arr;
            }
        } else {
            $ret = $arr;
        }
        return $ret;
    }

    /**
     * 添加查询记录
     *
     * @param Request $request
     *
     * @return \think\Response
     */
    public function addSearchLog(Request $request)
    {
        $param = $request::post();
        $userInfo = getLoginInfo();
        if ($userInfo == false) {
            return $this->returnJson(1004, '请先登录');
        }
        $data['user_id'] = $userInfo['id'];
        $data['company'] = $param['company'];
        $data['site'] = $param['site'];
        $data['email'] = $param['email'];
        $data['other'] = $param['other'];

        $find = Db::name('search_log')->where($data)->find();
        if($find !=false) {
            return $this->returnJson(1001, '已经存在');
        }

        $data['url'] = $param['url'];
        $data['title'] = $param['title'];
        $data['description'] = $param['description'];
        $data['create_time'] = toDate(time());

        $ret = Db::name('search_log')->save($data);
        if ($ret != false) {
            return $this->returnJson(1001, '保存成功', $param);
        } else {
            return $this->returnJson(1002, '保存失败');

        }

    }

}
